package com.diandian.backend.entrance.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.diandian.backend.entrance.client.DianDianMeiTuanShanGouClient;
import com.diandian.backend.entrance.client.dto.MeituanOrderKeyPointUploadDTO;
import com.diandian.backend.entrance.constants.EntranceConstant;
import com.diandian.backend.entrance.dto.ClientPermissionCacheDataDTO;
import com.diandian.backend.entrance.dto.GetProductSkuInfoReqDTO;
import com.diandian.backend.entrance.dto.MeiTuanShanGouStockSyncDTO;
import com.diandian.base.boot.starter.exception.DefaultException;
import com.diandian.base.boot.starter.response.BaseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 美团闪购
 */
@Service
public class RouterMeiTuanShanGouService {

    private static final Logger logger = LoggerFactory.getLogger(RouterMeiTuanShanGouService.class);

    @Autowired
    private DianDianMeiTuanShanGouClient dianDianMeiTuanShanGouClient;

    /**
     * 美团闪购子路由服务
     * @param clientInfoDTO 客户端信息
     * @param clientKey
     * @param clientSecret
     * @param data
     *      {
     *          "storeCode": "storeCode",
     *          "productCode": "productCode",
     *          “skuCode”: "skuCode",
     *          "stockCount": 0
     *      }
     * @return
     */
    public Object execute(ClientPermissionCacheDataDTO clientInfoDTO, String clientKey, String clientSecret, String cmd, JSONObject data)  throws Exception {

        // 查询商品sku库存信息
        if(EntranceConstant.ROUTER_MEITUAN_SHANGOU_STOCK_QUERY_SKU.equals(cmd)){

            logger.info("执行查询商品sku库存信息请求，参数: {}", data.toJSONString());

            // 获取配置信息
            String appKey = clientInfoDTO.getSettingValueFromSetting(EntranceConstant.SETTING_TYPE_MEITUAN_SHANGOU, EntranceConstant.SETTING_TYPE_MEITUAN_SHANGOU_APPKEY);
            String appSecret = clientInfoDTO.getSettingValueFromSetting(EntranceConstant.SETTING_TYPE_MEITUAN_SHANGOU, EntranceConstant.SETTING_TYPE_MEITUAN_SHANGOU_APPSECRET);
            String belong = clientInfoDTO.getSettingValueFromSetting(EntranceConstant.SETTING_TYPE_CLIENT, EntranceConstant.SETTING_TYPE_CLIENT_BELONG);

            if(appKey == null || "".equals(appKey) || appSecret == null || "".equals(appSecret) || belong == null || "".equals(belong)){
                throw new DefaultException("配置缺失");
            }

            // 门店编码校验：不为空校验、门店编码可操作校验
//            storeCodeCheck(clientInfoDTO, data);

            // 参数转换
            GetProductSkuInfoReqDTO dataDTO = JSONObject.parseObject(data.toString(), GetProductSkuInfoReqDTO.class);

            // 执行请求
            BaseResult resultDTO;
            try{
                resultDTO = dianDianMeiTuanShanGouClient.getProductSkuStockInfo(appKey, appSecret, belong, dataDTO);
            } catch (Exception e){
                logger.error("调用美团闪购服务异常", e);
                resultDTO = new BaseResult(500, "服务访问异常", e.getMessage());
            }

            logger.info("查询商品sku库存信息请求结果: {}", JSON.toJSONString(resultDTO));

            // 返回结果
            return resultDTO;
        }

        // 库存同步
        if(EntranceConstant.ROUTER_MEITUAN_SHANGOU_STOCK_SYNC.equals(cmd)){

            logger.info("执行库存同步请求，参数: {}", data.toJSONString());

            // 获取配置信息
            String appKey = clientInfoDTO.getSettingValueFromSetting(EntranceConstant.SETTING_TYPE_MEITUAN_SHANGOU, EntranceConstant.SETTING_TYPE_MEITUAN_SHANGOU_APPKEY);
            String appSecret = clientInfoDTO.getSettingValueFromSetting(EntranceConstant.SETTING_TYPE_MEITUAN_SHANGOU, EntranceConstant.SETTING_TYPE_MEITUAN_SHANGOU_APPSECRET);
            String belong = clientInfoDTO.getSettingValueFromSetting(EntranceConstant.SETTING_TYPE_CLIENT, EntranceConstant.SETTING_TYPE_CLIENT_BELONG);

            if(appKey == null || "".equals(appKey) || appSecret == null || "".equals(appSecret) || belong == null || "".equals(belong)){
                throw new DefaultException("配置缺失");
            }

            // 门店编码校验：不为空校验、门店编码可操作校验
//            storeCodeCheck(clientInfoDTO, data);

            // 参数转换
            MeiTuanShanGouStockSyncDTO syncDTO = JSONObject.parseObject(data.toString(), MeiTuanShanGouStockSyncDTO.class);

            // 执行请求
            BaseResult resultDTO;
            try{
                resultDTO = dianDianMeiTuanShanGouClient.skuStockUpdateOne(appKey, appSecret, belong, syncDTO);
            } catch (Exception e){
                logger.error("调用美团闪购服务异常", e);
                resultDTO = new BaseResult(500, "服务访问异常", e.getMessage());
            }

            logger.info("库存同步请求结果: {}", JSON.toJSONString(resultDTO));

            // 返回结果
            return resultDTO;
        }

        // 订单-上传关键节点
        if(EntranceConstant.ROUTER_MEITUAN_SHANGOU_ORDER_UPLOAD_KEY_POINT.equals(cmd)){

            logger.info("执行上传关键节点请求，参数: {}", data.toJSONString());

            // 获取配置信息
            String appKey = clientInfoDTO.getSettingValueFromSetting(EntranceConstant.SETTING_TYPE_MEITUAN_SHANGOU, EntranceConstant.SETTING_TYPE_MEITUAN_SHANGOU_APPKEY);
            String appSecret = clientInfoDTO.getSettingValueFromSetting(EntranceConstant.SETTING_TYPE_MEITUAN_SHANGOU, EntranceConstant.SETTING_TYPE_MEITUAN_SHANGOU_APPSECRET);

            if(appKey == null || "".equals(appKey) || appSecret == null || "".equals(appSecret)){
                throw new DefaultException("配置缺失");
            }

            // 参数转换
            MeituanOrderKeyPointUploadDTO syncDTO = JSONObject.parseObject(data.toString(), MeituanOrderKeyPointUploadDTO.class);

            // 执行请求
            BaseResult resultDTO;
            try{
                resultDTO = dianDianMeiTuanShanGouClient.keyPointUpload(appKey, appSecret, syncDTO);
            } catch (Exception e){
                logger.error("调用美团闪购服务异常", e);
                resultDTO = new BaseResult(500, "服务访问异常", e.getMessage());
            }

            logger.info("上传关键节点结果: {}", JSON.toJSONString(resultDTO));

            // 返回结果
            return resultDTO;
        }

        // 根据原商品编码更换新商品编码 todo 待测试
//        if(EntranceConstant.ROUTER_MEITUAN_SHANGOU_PRODUCT_CODE_UPDATE.equals(cmd)){
//            logger.info("执行商品编码请求，参数: {}", data.toJSONString());
//
//            // 获取配置信息
//            String appKey = clientInfoDTO.getSettingValueFromSetting(EntranceConstant.SETTING_TYPE_MEITUAN_SHANGOU, EntranceConstant.SETTING_TYPE_MEITUAN_SHANGOU_APPKEY);
//            String appSecret = clientInfoDTO.getSettingValueFromSetting(EntranceConstant.SETTING_TYPE_MEITUAN_SHANGOU, EntranceConstant.SETTING_TYPE_MEITUAN_SHANGOU_APPSECRET);
//            if(appKey == null || "".equals(appKey) || appSecret == null || "".equals(appSecret)){
//                throw new DefaultException("配置缺失");
//            }
//
//            // 门店编码校验：不为空校验、门店编码可操作校验
//            storeCodeCheck(clientInfoDTO, data);
//
//            // 参数转换
//            ProductUpdateAppFoodCodeByOriginDTO syncDTO = new ProductUpdateAppFoodCodeByOriginDTO();
//            syncDTO.setApp_poi_code(data.getString("offlineStoreCode"));
//            syncDTO.setApp_spu_code_origin(data.getString("productCodeOrigin"));
//            syncDTO.setApp_spu_code(data.getString("productCode"));
//            syncDTO.setSku_id_origin(data.getString("skuCodeOrigin"));
//            syncDTO.setSku_id(data.getString("skuCode"));
//
//            // 执行请求
//            BaseResult resultDTO;
//            try{
//                resultDTO = dianDianMeiTuanShanGouClient.updateAppFoodCodeByOrigin(appKey, appSecret, syncDTO);
//            } catch (Exception e){
//                logger.error("调用美团闪购服务异常", e);
//                resultDTO = new BaseResult(500, "服务访问异常", e.getMessage());
//            }
//
//            logger.info("商品编码请求结果: {}", JSON.toJSONString(resultDTO));
//
//            // 返回结果
//            return resultDTO;
//        }

        throw new DefaultException("暂不支持此操作");
    }

    /**
     * 校验门店编码合法性：门店编码在可操作的数据范围内
     * @param clientInfoDTO
     * @param data
     */
    private void storeCodeCheck(ClientPermissionCacheDataDTO clientInfoDTO, JSONObject data){
        // 校验门店是否在范围内
        List<String> meiTuanShanGouStoreCodes = clientInfoDTO.getMeiTuanShanGouStoreCodes();
        if(meiTuanShanGouStoreCodes == null || meiTuanShanGouStoreCodes.size() == 0){
            throw new DefaultException("暂无可操作的门店");
        }
        String onlineStoreCode = data.getString("onlineStoreCode");
        String offlineStoreCode = data.getString("offlineStoreCode");
        if((onlineStoreCode == null || "".equals(onlineStoreCode)) && (offlineStoreCode == null || "".equals(offlineStoreCode))){
            throw new DefaultException("门店编码不能为空");
        }
        if(!meiTuanShanGouStoreCodes.contains(onlineStoreCode) && !meiTuanShanGouStoreCodes.contains(offlineStoreCode)){
            throw new DefaultException("暂不可操作此门店");
        }
    }
}
